<template>
  <a-modal size="mini" class="modal-con" :visible="visible" @before-open="open" :on-before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="45%" :mask-closable="false">
    <template #title> 设置库存单价 </template>
    <div>
      <a-tabs size="mini" v-model:active-key="currentPage">
        <a-tab-pane key="1" title="单个设置">
          <a-table size="mini" class="table-singe-line" :pagination="false" :data="tableList" :scroll="{ y: 400 }" style="margin-top: 10px">
            <template #columns>
              <a-table-column title="仓库">
                <template #cell="{ record, rowIndex }"> {{ record.warehouseName }}({{ record.warehouseCode }}) </template>
              </a-table-column>
              <a-table-column title="店铺">
                <template #cell="{ record }">
                  {{ record.shopName }}
                </template>
              </a-table-column>
              <a-table-column title="图片">
                <template #cell="{ record }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column title="SKU" :width="140">
                <template #cell="{ record }">
                  {{ record.sku }}
                </template>
              </a-table-column>
              <a-table-column title="MSKU" :width="140">
                <template #cell="{ record }">
                  {{ record.msku }}
                </template>
              </a-table-column>
              <!-- :sortable="{ sortDirections: ['ascend', 'descend'] }" -->
              <a-table-column :width="160">
                <template #title>
                  <div>库存单价</div>
                  <div style="display: flex">
                    <a-input-number hide-button v-model="titleFormValue.price" />
                    <a-button size="small" class="gray-outline" style="margin-left: 5px" @click="setPrice">
                      <template #icon>
                        <icon-double-down />
                      </template>
                    </a-button>
                  </div>
                </template>
                <template #cell="{ record }">
                  <a-input-number hide-button v-model="record.avgPrice" />
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" title="批量导入">
          <div>
            <a-form auto-label-width ref="formRef" size="medium" :model="form">
              <a-space direction="vertical" :size="24" style="margin-top: 10px">
                <a-row>
                  <a-col :span="24">
                    <a-form-item field="warehouseCode" label="选择仓库" :rules="rules.warehouseCode">
                      <a-select placeholder="请选择仓库" v-model="form.warehouseCode" allow-clear>
                        <a-option v-for="item of houseList" :label="item.warehouseName" :value="item.warehouseCode"></a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="24">
                    <a-form-item field="file" label="选择文件" class="upload" :rules="rules.file">
                      <a-upload v-if="visible" action="#" :auto-upload="false" @before-remove="beforeRemove" @before-upload="beforeUpload" />
                      <a-button type="text" class="text" @click="downloadTemplate">点击下载模板</a-button>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-space>
            </a-form>
          </div>
          <div class="footer-text">
            <p>支持导入格式为xls的文件</p>
            <p> 模板中的表头不可更改、位置不能调换，不能删除</p>
            <p>店铺+SKU+MSKU是唯一值，如果出现重复，以第一条记录为准 每次导入将覆盖已有的数据</p>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { updatePriceBatch, updatePriceImport } from '@/api/inventory'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['list'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        form: {},
        rules: {
          warehouseCode: [{ required: true, message: '请选择仓库' }],
          file: [{ required: true, message: '请选择文件' }],
        },
        titleFormValue: {
          price: '',
        },
        houseList: [],
        currentPage: '1',
        tableList: [],
      })

      const open = () => {
        console.log(props.list)

        getWareHouseList()
        data.tableList = _.cloneDeep(props.list)
      }
      const handleOk = async (done: any) => {
        let res: any = {}
        if (data.currentPage == '1') {
          let params: any = {
            itemParams: [],
          }
          data.tableList.forEach((e: any) => {
            if (e.avgPrice) {
              let obj: any = {}
              obj.inventoryId = e.id
              obj.avgPrice = e.avgPrice
              params.itemParams.push(obj)
            }
          })
          try {
            res = await updatePriceBatch(params)
          } catch (error) {
            done(true)
          }
        } else {
          formRef.value.validate(async (valid: any) => {
            if (!valid) {
              let params = new FormData()
              params.append('file', data.form.file)
              params.append('warehouseCode', data.form.warehouseCode)
              try {
                res = await updatePriceImport(params)
              } catch (error) {
                done(true)
              }
            } else {
              done(true)
            }
          })
        }

        if (res.code == 'SUCCESS') {
          data.form = {}
          Message.success('修改成功')
          visible.value = false
          emit('save')
        }
        done(true)
      }
      const handleCancel = () => {
        visible.value = false
      }
      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        data.houseList = res.data
      }
      const setPrice = () => {
        data.tableList.map((e: any) => {
          e.avgPrice = data.titleFormValue.price
          return e
        })
      }
      const downloadTemplate = () => {
        let a = document.createElement('a')
        a.href = 'https://cdn2.selleroa.com/saas/inventory/85372756787051521.xls'
        a.click()
        a.style.display = 'none'
      }

      const beforeUpload = (file: any) => {
        const extension = file.name.substring(file.name.lastIndexOf('.') + 1)

        if (data.form.file) {
          Message.error('每次只能上传一个excel文件')
          return
        }

        if (!['xls', 'xlsx'].includes(extension)) {
          Message.error('只能上传excel文件')
          return
        }
        data.form.file = file
        console.log(data.form)

        return true
      }

      const beforeRemove = () => {
        data.form.file = null
        return true
      }
      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        setPrice,
        downloadTemplate,
        beforeUpload,
        beforeRemove,
      }
    },
  })
</script>

<style lang="less" scoped>
  .modal-con {
    .arco-drawer {
      :deep(.arco-modal-body) {
        padding: 10px !important;
      }
    }
  }

  .upload {
    position: relative;
    :deep(.arco-upload-progress) {
      display: none;
    }
  }

  .text {
    position: absolute;
    left: 180px;
    top: 0;
  }

  .footer-text {
    font-size: 12px;
    color: darkgray;
  }
</style>
